package org.fitweb.files;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class PathFinder {

    public static String canonical(String path) {
        return canonical(new File(path));
    }

    public static String canonical(String base, String extension) {
        return canonical(new File(base, extension));
    }

    public static String canonical(File file) {
        try {
            return file.getCanonicalPath();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static String relativePath(String ancestorPath, String descendantPath) {
        return relativeFile(new File(ancestorPath), new File(descendantPath)).getPath();
    }

    public static File relativeFile(File ancestor, File descendant) {
        String descendantPath = descendant.getPath();
        String ancestorPath = ancestor.getPath();

        if (descendant.isAbsolute()) {
            descendantPath = canonical(descendant);
            ancestorPath = canonical(ancestor);
        }

        return new File(descendantPath
                .replace(ancestorPath, "")
                .replaceFirst("^[/|\\\\]", ""));
    }

    public static Collection<File> relativeFiles(File ancestor, Collection<File> absoluteFiles) {
        Collection<File> relativeFiles = new ArrayList<File>();
        for (File absoluteFile : absoluteFiles) {
            relativeFiles.add(relativeFile(ancestor, absoluteFile));
        }
        return relativeFiles;
    }
}
